//
//  NetworkTools.swift
//  测试-05-AFN Swift
//
//  Created by male on 15/10/15.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking

/// HTTP 请求方法枚举
enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: 网络工具
class NetworkTools: AFHTTPSessionManager {
    private let clientId = "3849332272"
    private let redirect = "http://www.baidu.com"
    private let appSecret = "1daadb4cb56c5958451c526863320500"
    // 定义网络请求回调
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()
    /// 单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
//    /// token 字典
//    private var tokenDict: [String:AnyObject]?{
//        if let token = HMUserAcountViewModel.sharedUserAccount.token {
//            return ["access_token":token]
//        }
//        return nil
//    }
}
// MARK: -发布微博
extension NetworkTools {
    func sendStatus(status: String, finished:HMRequestCallBack) {
        var parameters = [String: AnyObject]()
        parameters["status"] = status
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        tokenRequest(.POST, URLString: urlString, parameters: parameters, finished: finished)
    }
}
// MARK: - 微博相关数据
extension NetworkTools {
    /**
        since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
        max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0
    18332553548
    */
    func loadStatus(since_id since_id: Int, max_id: Int, finished:HMRequestCallBack){
        var parameters = [String: AnyObject]()
        if since_id > 0 {
            parameters["since_id"] = since_id
        }else if max_id > 0 {
            parameters["max_id"] = max_id - 1
        }
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        tokenRequest(.GET, URLString: urlString, parameters: parameters, finished: finished)
    }
}

// MARK: -用户信息
extension NetworkTools{
    
    func loadUserInfo(uid:String,finished:HMRequestCallBack){
        var parameters = [String: AnyObject]()
        let urlString = "https://api.weibo.com/2/users/show.json"
        parameters["uid"] = uid
        tokenRequest(.GET, URLString: urlString, parameters: parameters, finished: finished)
    }
}
// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    private func tokenRequest(method: HMRequestMethod, URLString: String, var parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        
        // 1. 将token添加到字典
        guard let token = HMUserAcountViewModel.sharedUserAccount.token else {
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["信息错误":"token为空"]))
            return
        }
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = token
        // 2.发送网络请求
        request(method, URLString: URLString, parameters: parameters, finished: finished)
    }
    // 获取token
    func getToken(code: String,finished: HMRequestCallBack){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let dict = ["client_id":clientId,
        "client_secret":appSecret,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":redirect]
        request(.POST, URLString: urlString, parameters: dict, finished: finished)
    }
    // 请求验证
    var oauthURL: NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirect)"
        return NSURL(string: urlString)!
    }
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    func request(method: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }

    }
}
